package models

import (
	"cashew.com/cashew_api/dtos"
	"github.com/beego/beego/v2/client/orm"
)

type Sub_region_configuration struct {
	RegionId     int
	MainRegionId int
	RegionName   string `orm:"size(128)"`
	RegionCode   string `orm:"size(128)"`
	FlagImage    string `orm:"size(128)"`
}

func init() {
	orm.RegisterModel(new(Sub_region_configuration))
}

func GetSub_region_configurationByCode(code string) (v *Sub_region_configuration, err error) {
	o := orm.NewOrm()
	v = &Sub_region_configuration{}
	if err = o.QueryTable(new(Sub_region_configuration)).Filter("region_code", code).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return v, err
}

func GetSub_region_configurationByRegionId(regionId int) (v *Sub_region_configuration, err error) {
	o := orm.NewOrm()
	v = &Sub_region_configuration{}
	if err = o.QueryTable(new(Sub_region_configuration)).Filter("region_id", regionId).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return v, err
}

func GetSub_region_configurationByPage(offset, limit int) (*[]dtos.RegionGetSubRegionListItem, error) {
	qb, _ := orm.NewQueryBuilder("mysql")
	o := orm.NewOrm()
	fields := "src.region_id sub_region_id,src.region_name sub_region_name,src.region_name_client sub_region_name_client,src.region_code sub_region_code, src.flag_image sub_region_flag, mrc.region_id main_region_id, mrc.region_name main_region_name"
	sql := qb.Select(fields).From("sub_region_configuration src").
		LeftJoin("main_region_configuration mrc").On("src.main_region_id = mrc.region_id").
		Where("src.region_id > 0").
		OrderBy("src.region_id").Asc().Limit(limit).Offset(offset).String()

	list := []dtos.RegionGetSubRegionListItem{}

	_, err := o.Raw(sql).QueryRows(&list)

	return &list, err
}

func GetSub_region_configurationCount() (int64, error) {
	o := orm.NewOrm()
	count, err := o.QueryTable(new(Sub_region_configuration)).Count()
	if err != nil {
		return 0, err
	}
	return count, nil
}
